#pragma once 
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
#include <fcntl.h>
#include <unistd.h>

const std::string ggpath = "./fifo";
const mode_t ggmode = 0600;
const int gWriteFlag = O_WRONLY;
const int gReadFlag = O_RDONLY;

class Pipe{
private:
    void OpenPipe(int flags)
    {
        _fd = ::open(ggpath.c_str(),flags);
        if (_fd < 0){
            std::cerr << "open file error" << std::endl;
            exit(2);
        }
        std::cout << "open success" << std::endl;
    }
public:
    Pipe()  :_fd(-1)
    {
        std::cout << "我这不是全局的吗？" << std::endl;
        umask(0);
        int n = mkfifo(ggpath.c_str(),ggmode);
        if (n < 0){
            // std::cerr << "mkfifo error" << std::endl; 这里直接忽略这个问题，为了测试
        }
        std::cout << "mkfifo success" << std::endl;

    }
    void OpenForWrite(){
        OpenPipe(gWriteFlag);
    }
    void OpenForRead(){
        OpenPipe(gReadFlag);
    }
    void Wait(){
        std::cout << "fd: " << _fd << std::endl;
        int cmd;
        int n = ::read(_fd,&cmd,sizeof(cmd));
        if (n > 0){
            //
            std::cout << "读到了数据，开始执行下面的任务" << std::endl;
            // sleep(1);
            return;
        }
        else if(n == 0){
            std::cout << "client quit" << std::endl;
            // sleep(1);
            return;
        }
        else{
            //;
        }
    }
    void Signal()
    {
        int cmd = 1;
        ::write(_fd,&cmd,sizeof(cmd));
    }
    ~Pipe(){
        if (_fd > 0) ::close(_fd);
        int n = ::unlink(ggpath.c_str());
        if (n < 0){
            std::cerr << "unlink error" << std::endl;
        }
        std::cout << "unlink success" << std::endl;
    }
private:
    int _fd;
};


Pipe gpipe;